package com.xiaoihu.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.xiaoihu.server.pojo.Employee;
import com.xiaoihu.server.pojo.MailConstants;
import com.xiaoihu.server.pojo.MailLog;
import com.xiaoihu.server.service.IEmployeeService;
import com.xiaoihu.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: xiaoihu
 * @Description: 邮件发送定时任务
 * @Date Created in 2022-04-18 18:47
 * @Modified By:
 */
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务
     * 10s发送一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        //查出没超时且状态还在发送中的消息
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("tryTime", LocalDateTime.now())
        );
        //循环重新发送
        list.forEach(mailLog -> {
            if (MailConstants.MAX_TRY_COUNT <=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2)
                        .eq("msgId",mailLog.getMsgId())
                );
            }else {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("count",mailLog.getCount()+1)
                        .set("updateTime",LocalDateTime.now())
                        .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MAX_TIME_OUT))
                        .eq("msgId",mailLog.getMsgId())
                );
                //重新获取员工信息
                Employee emp = employeeService.getEmployee(mailLog.getEid()).get(0);
                //重新发送消息
                rabbitTemplate.convertAndSend(
                        MailConstants.MAIL_EXCHANGE_NAME,
                        MailConstants.MAIL_ROUTING_KEY_NAME,
                        emp,
                        new CorrelationData(mailLog.getMsgId())
                        );
            }
        });

    }
}
